package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    //依赖注入mapper层 订单表
    @Autowired
    private OrderMapper orderMapper;

    //依赖注入mapper层 地址表
    @Autowired
    private AddressMapper addressMapper;

    /*依赖注入mapper层 购物车表
    private CartMapper cartMapper;*/

    //依赖注入service层 购物车表
    @Autowired
    private CartService cartService;

    //依赖注入mapper层 订单细节表
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    //提交订单
    @Override
    public void submit(Order order) {
        //业务处理
        //1.获取到当前用户
        User user = UserHolder.get();
        //判空
        if (user==null) {
            throw new CustomException("登录用户不能为空...");
        }
        //2.根据addressId查询address表
        Address address = addressMapper.selectById(order.getAddressId());
        //判空
        if (address==null) {
            throw new CustomException("收货地址不能为空...");
        }
        //3.根据用户id查询购物车信息
        List<Cart> cartList = cartService.findList();
        //List<Cart> cartList = cartMapper.selectList(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, user.getId()));
        //判空
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException(("购物车内为空不能提交..."));
        }

        //生成订单id
        long orderId = IdWorker.getId(); //mp的id生成器(雪花)

        //订单金额
        BigDecimal amount = new BigDecimal(0);

        //4.遍历购物车列表
        for (Cart cart : cartList) {
            //4-1新建订单细节对象
            OrderDetail orderDetail = new OrderDetail();
            //4-2补充信息
            orderDetail.setName(cart.getName());    //套餐或菜品名
            orderDetail.setImage(cart.getImage());  //套餐或菜品图片地址
            orderDetail.setOrderId(orderId);    //关联order的id
            orderDetail.setSetmealId(cart.getSetmealId());  //套餐名
            orderDetail.setDishId(cart.getDishId());    //菜品名
            orderDetail.setDishFlavor(cart.getDishFlavor());    //菜品口味
            orderDetail.setNumber(cart.getNumber());    //数量
            orderDetail.setAmount(cart.getAmount());    //金额

            //4-3调用mp新增
            orderDetailMapper.insert(orderDetail);

            //4-4累加金额数目
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        //5.保存订单
        //5-1补全信息
        order.setId(orderId);   //订单主键
        order.setNumber(String.valueOf(orderId));   //订单号
        order.setStatus(1);     //待支付
        order.setUserId(user.getId());  //用户id
        order.setOrderTime(new Date()); //下单时间
        order.setCheckoutTime(new Date());  //查询时间
        order.setAmount(amount);    //总支付金额
        order.setPhone(address.getPhone()); //电话号
        order.setAddress(address.getDetail());  //下单地址
        order.setUserName(user.getName());  //用户名
        order.setConsignee(address.getConsignee()); //收货人

        //5-2调用mp新增
        orderMapper.insert(order);

        //6.清空购物车
        cartService.clean();

    }

    //查询订单列表 + 模糊查询 + 时间查询
    @Override
    public Page<Order> findList(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {
        //业务处理
        //0.创建条件构造器
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        //1.设置模糊查询条件
        qw.like(StrUtil.isNotBlank(number),Order::getNumber,number);    //判空
        //2.设置起始条件查询
        //qw.between(ObjectUtil.isAllNotEmpty(beginTime,endTime),Order::getCheckoutTime, DateUtil.formatDate(beginTime), DateUtil.formatDate(endTime));   //糊涂工具包判空
        //qw.between(beginTime!=null && endTime!=null,Order::getCheckoutTime, DateUtil.formatDateTime(beginTime), DateUtil.formatDateTime(endTime));   //糊涂工具包判空
        qw.between(beginTime != null && endTime != null,Order::getCheckoutTime, beginTime, endTime);   //
        //3.按照订单完成时间降序
        qw.orderByDesc(Order::getCheckoutTime);
        //3.开启分页
        Page<Order> page = new Page<>(pageNum,pageSize);
        //4.调用mp查询
        return orderMapper.selectPage(page,qw);
    }

    //历史订单页面
    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize) {
        //业务处理

        //获取当前用户对象
        User user = UserHolder.get();
        //判空
        if (user==null) {
            //若空,抛出异常
            throw new CustomException("登录用户不能为空...");
        }
        //创建变量用于存放商品个数
        Integer sum = 0;

        //0.创建条件构造器
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        //1.设置条件 降序  + 当前用户
        qw.orderByDesc(Order::getCheckoutTime);
        qw.eq(Order::getUserId,user.getId());
        //2.开启分页查询
        Page<Order> page = new Page<>(pageNum,pageSize);
        //3.调用mp查询
        page = orderMapper.selectPage(page,qw);

        //4.遍历
        //遍历订单列表
        for (Order order : page.getRecords()) {
            //4-1.查询orderdetail表
            List<OrderDetail> detailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, order.getId()));
            //4-2.将表内数据添加到order中
            order.setOrderDetails(detailList);
            //4-3.计算商品数目
            for (OrderDetail orderDetail : detailList) {
                sum += sum + orderDetail.getNumber();
            }
            //4-4.设置商品数目
            order.setSumNum(sum);
        }

        //返回数据
        return page;
    }
}
